package cn.ibdsr.human.service.impl;

import cn.ibdsr.human.constant.IsDeleted;
import cn.ibdsr.human.constant.JobStatusEnum;
import cn.ibdsr.human.constant.PlatformEnum;
import cn.ibdsr.human.constant.ServerInitEnum;
import cn.ibdsr.human.db.mapper.*;
import cn.ibdsr.human.db.model.*;
import cn.ibdsr.human.exception.BizExceptionEnum;
import cn.ibdsr.human.exception.BusinessException;
import cn.ibdsr.human.service.CompanyRecommendService;
import cn.ibdsr.human.service.DataCenterService;
import cn.ibdsr.human.service.JobService;
import cn.ibdsr.human.transfer.companyrecommend.CompanyRecommendDTO;
import cn.ibdsr.human.transfer.companyrecommend.CompanyRecommendImgDTO;
import cn.ibdsr.human.transfer.platform.LatestJobItem;
import cn.ibdsr.human.util.HttpServletUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: cdl
 * @email: iamcimon@qq.com
 * @date: 2021/8/12 15:55
 */
@Service
@Slf4j
public class DataCenterServiceImpl implements DataCenterService {
    protected static final Logger LOGGER = LoggerFactory.getLogger(DataCenterServiceImpl.class);
    @Resource
    private JobService jobService;
    @Resource
    private CompanyRecommendService companyRecommendService;
    @Resource
    private CompanyRecommendImgMapper companyRecommendImgMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserDetailMapper userDetailMapper;
    @Resource
    private JobMapper jobMapper;

    @Resource
    private ServerInitMapper serverInitMapper;

    @Override
    public String getDataCenterData() {
        JSONObject result = new JSONObject();
        /////////////////////////////推荐工作/////////////////////////////////
        List<LatestJobItem> latestJobItems = jobService.getLatestJob();
        if (latestJobItems.size() > 0) {

            JSONArray array = JSONArray.parseArray(JSONObject.toJSONString(latestJobItems));
            result.put("jobs", array);
        }
        /////////////////////////////推荐企业/////////////////////////////////
        List<CompanyRecommendDTO> latestCompanies = companyRecommendService.getLatestCompanies();
        List<Long> ids = new ArrayList<>();
        ConcurrentHashMap<Long, List<CompanyRecommendImgDTO>> imagesMap = new ConcurrentHashMap<>();
        if (latestCompanies.size() > 0) {
            for (CompanyRecommendDTO companyRecommendDTO : latestCompanies) {
                ids.add(companyRecommendDTO.getId());
            }
            QueryWrapper<CompanyRecommendImg> companyRecommendImgQueryWrapper = new QueryWrapper<>();
            companyRecommendImgQueryWrapper.in("company_id", ids);
            companyRecommendImgQueryWrapper.eq("is_deleted", IsDeleted.NORMAL.getCode());
            List<CompanyRecommendImg> companyRecommendImgs = companyRecommendImgMapper.selectList(companyRecommendImgQueryWrapper);
            for (int i = 0; i < companyRecommendImgs.size(); i++) {
                CompanyRecommendImg companyRecommendImg = companyRecommendImgs.get(i);
                CompanyRecommendImgDTO companyRecommendImgDTO = JSONObject.parseObject(JSONObject.toJSONString(companyRecommendImg), CompanyRecommendImgDTO.class);
                if (imagesMap.containsKey(companyRecommendImg.getCompanyId())) {
                    List<CompanyRecommendImgDTO> strings = imagesMap.get(companyRecommendImg.getCompanyId());
                    strings.add(companyRecommendImgDTO);
                } else {
                    List<CompanyRecommendImgDTO> strings = new ArrayList<>();
                    strings.add(companyRecommendImgDTO);
                    imagesMap.put(companyRecommendImg.getCompanyId(), strings);
                }

            }
            for (CompanyRecommendDTO companyRecommendDTO : latestCompanies) {
                companyRecommendDTO.setUrls(imagesMap.get(companyRecommendDTO.getId()));
            }
            JSONArray array = JSONArray.parseArray(JSONObject.toJSONString(latestCompanies));
            result.put("companies", array);
        }
        QueryWrapper<User> companyWrapper = new QueryWrapper<User>();
        companyWrapper.eq("is_deleted", IsDeleted.NORMAL.getCode());
        companyWrapper.eq("sys_type", PlatformEnum.COMPANY.getCode());
        Integer companyNum = userMapper.selectCount(companyWrapper);

        result.put("companyNum", companyNum);// 企业数量

        QueryWrapper<User> userWrapper = new QueryWrapper<User>();
        userWrapper.eq("is_deleted", IsDeleted.NORMAL.getCode());
        userWrapper.eq("sys_type", PlatformEnum.USER.getCode());
        Integer workerNum = userMapper.selectCount(userWrapper);
        result.put("workerNum", workerNum);// 简历总份数

        QueryWrapper<UserDetail> userDetailQueryWrapper = new QueryWrapper<UserDetail>();
        userDetailQueryWrapper.eq("is_deleted", IsDeleted.NORMAL.getCode());
        userDetailQueryWrapper.eq("job_status", JobStatusEnum.FINDING.getType());
        Integer findJobNum = userDetailMapper.selectCount(userDetailQueryWrapper);
        result.put("findJobNum", findJobNum);// 求职中人数

        QueryWrapper<Job> jobQueryWrapper = new QueryWrapper<Job>();
        jobQueryWrapper.eq("is_deleted", IsDeleted.NORMAL.getCode());
        Integer jobNum = jobMapper.selectCount(jobQueryWrapper);
        result.put("jobNum", jobNum);// 求职中人数

        QueryWrapper<ServerInit> serverInitQueryWrapper = new QueryWrapper<>();
        serverInitQueryWrapper.eq("type", ServerInitEnum.SERVER_PHONE.getType());
        ServerInit serverInit = serverInitMapper.selectOne(serverInitQueryWrapper);
        if (serverInit == null) {
            throw new BusinessException(BizExceptionEnum.SERVIER_INIT_ERROR);
        }
        result.put("phone", String.valueOf(serverInit.getConfigValue()));//

        return result.toJSONString();

    }

    @Override
    public void backup() {
        String backupsSqlFileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String fileName = "human_resource" + backupsSqlFileName + ".sql";
        HttpServletResponse response = HttpServletUtils.getResponse();
        ServletOutputStream out = null;
        try {
            String mysql = "docker exec human_mysql_1 mysqldump -uroot -phuman_mysql_001 --set-gtid-purged=off --databases human_resource";
            mysql = mysql + " --default-character-set=utf8";
            LOGGER.info("cmd命令为：——>>>" + mysql);
            Runtime runtime = Runtime.getRuntime();
            Process child = runtime.exec(mysql);
            // 读取备份数据并生成文件
            InputStream in = child.getInputStream();
            response.reset();
            response.setContentType("multipart/form-data");
            String newFileName = new String(fileName);
            response.setHeader("Content-Disposition", "attachment; filename=" + newFileName);
            out = response.getOutputStream();
            int len = 0;
            //创建数据缓冲区
            byte[] buffer = new byte[1024];
            //将FileInputStream流写入到buffer缓冲区
            while ((len = in.read(buffer)) > 0) {
                //使用BufferedOutputStream将缓冲区的数据输出到指定位置文件
                out.write(buffer, 0, len);
            }
            out.flush();
            in.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
